package com.monkeyboy.my;

import java.util.ArrayList;
import java.util.concurrent.CountDownLatch;

/**
 * 千万数据量的list添加
 *
 * @Author Gavin
 * @date 2021.05.19 10:48
 */
public class ListFindObj {
    private static volatile boolean flag = false;
    static CountDownLatch count = new CountDownLatch(8);

    public static void main(String[] args) throws InterruptedException {
        ArrayList<Integer> list = new ArrayList(40000000);
        for (int i = 0; i < 40000000; i++) {
            list.add(i);
        }
        System.out.println("数据准备好了,一共："+list.size()+" 条数据");
        System.out.println("开始查找数据--------------------");
        Thread.sleep(2000);
        long start=System.currentTimeMillis();
        new Find(0, 5000000, list).start();
        new Find(5000000, 10000000, list).start();
        new Find(10000000, 15000000, list).start();
        new Find(15000000, 20000000, list).start();
        new Find(20000000, 25000000, list).start();
        new Find(25000000, 30000000, list).start();
        new Find(30000000, 35000000, list).start();
        new Find(35000000, 40000000, list).start();

//        new Find(0, 40000000, list).start();

        while (!flag){
        }
        long end=System.currentTimeMillis();
        System.out.println("总共花费时间为： "+(end-start));
    }

    static class Find extends Thread {
        private int begin;
        private int end;
        private ArrayList<Integer> list;

        public Find(int begin, int end, ArrayList list) {
            this.begin = begin;
            this.end = end;
            this.list = list;
        }

        @Override
        public void run() {
            try {
                count.countDown();
                count.await();
                for (int i = begin; i < end; i++) {
                    if (flag) {
                        break;
                    } else {
                        if (list.get(i)==39999998) {
                            System.out.println(i);
                            flag = true;
                        }
                    }
                }
            } catch (Exception e) {
            }

        }
    }
}
